package com.browan.demo.http;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.util.Log;

public class MeetingApi {

	private static MeetingApi mInstance = null;
	

	private final String HOST = "210.14.78.211";
	private final String REG_URL = "/mobile_demo/meeting_demo_register.php";
	private final String FRD_URL = "/mobile_demo/meeting_demo_get_friends.php";
	private final String STM_URL = "/mobile_demo/meeting_demo_start_meeting.php";
	private final String STS_URL = "/mobile_demo/meeting_demo_get_status.php";

	private DefaultHttpClient mClient;

	public static MeetingApi getInstance() {

		if (mInstance == null)
			mInstance = new MeetingApi();
		return mInstance;
	}

	private MeetingApi() {
		if (null == mClient) {
			HttpParams params = new BasicHttpParams();

			HttpConnectionParams.setTcpNoDelay(params, true);
			HttpClientParams.setRedirecting(params, true);
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
			HttpProtocolParams.setUseExpectContinue(params, false);
			HttpConnectionParams.setSocketBufferSize(params, 8192);

			SchemeRegistry supportedSchemes = new SchemeRegistry();
			supportedSchemes.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			supportedSchemes.register(new Scheme("Https", SSLSocketFactory
					.getSocketFactory(), 443));
			ClientConnectionManager ccm = new ThreadSafeClientConnManager(
					params, supportedSchemes);
			mClient = new DefaultHttpClient(ccm, params);
		}

	}

	private HttpParams createDefaultHttpParams() {
		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setSoTimeout(params, 5000);
		HttpConnectionParams.setConnectionTimeout(params, 5000);
		//HttpProtocolParams.setUserAgent(params, "FreePP.Meeting.Demo");
		return params;
	}

	private void closeHttpEntity(HttpEntity httpEntity) {
		if (null != httpEntity) {
			// 关闭流
			if (httpEntity.isStreaming()) {
				try {
					Closeable is = httpEntity.getContent();
					if (is != null) {
						is.close();
					}
				} catch (IllegalStateException e) {
				} catch (IOException e) {
				}
			}
			
			// 释放链接
			try {
				httpEntity.consumeContent();
			} catch (IOException e) {
				e.printStackTrace();
			}
			httpEntity = null;
		}
	}
	
	private MeetingReturned parseResponse(HttpEntity entity) {
		if(entity == null) return null;
	
		BufferedReader reader = null;
		InputStream is = null;
		MeetingReturned returned = null;
		
		try {
			is = entity.getContent();
			reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8));
			String line;
			returned = new MeetingReturned();
			while ((line = reader.readLine()) != null)
			{
				String[] array = line.split("=");
				String k = new String(array[0]);
				String v = new String(array[1]);
				if(k.equals("result")) {
					returned.isSuccess = v.equals("1");
				}
				else if(k.equals("freeppid")) {
					returned.freeppid = v;
				}
				else if(k.equals("members")) {
					returned.members = v.split(",");
				}
			}
		} catch (IllegalStateException e) {
		} catch (IOException e) {
		}
		finally
		{
			if(reader!=null)
				try {
					if(reader!=null) reader.close();
					if(is!=null)is.close();
				} catch (IOException e) {
				}
		}
		
		return returned;
	}
	
	private MeetingReturned post(HttpPost postReq) {
		HttpHost host = new HttpHost(HOST, 80);
		HttpResponse response = null;
		MeetingReturned returned = null;
		try {
			response = mClient.execute(host, postReq);
			int retCode = response.getStatusLine().getStatusCode();
			if (retCode == HttpStatus.SC_OK) {
				returned = parseResponse(response.getEntity());
			}
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
			Log.e("Meeting", "IOE", e);
		} finally {
			if (null != response) {
				closeHttpEntity(response.getEntity());
			}
		}
		return returned;
	}

	public MeetingReturned register(String e164Number) {
		HttpPost postReq = new HttpPost(REG_URL);
		postReq.setParams(createDefaultHttpParams());

		ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
		NameValuePair nvp = new BasicNameValuePair("mobile", e164Number);
		paramList.add(nvp);
		try {
			postReq.setEntity(new UrlEncodedFormEntity(paramList, HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {
			return null;
		}

		return post(postReq);
	}

	public MeetingReturned getFriends() {
		HttpPost postReq = new HttpPost(FRD_URL);
		postReq.setParams(createDefaultHttpParams());

		ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
	
		try {
			postReq.setEntity(new UrlEncodedFormEntity(paramList, HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {
			return null;
		}

		return post(postReq);
	}

	public MeetingReturned startMeeting(String self, String others) {
		HttpPost postReq = new HttpPost(STM_URL);
		postReq.setParams(createDefaultHttpParams());

		ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
		NameValuePair nvp = new BasicNameValuePair("mobile", self);
		paramList.add(nvp);
		NameValuePair nvp2 = new BasicNameValuePair("members", others);
		paramList.add(nvp2);
		try {
			postReq.setEntity(new UrlEncodedFormEntity(paramList, HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {
			return null;
		}

		return post(postReq);
	}

	public MeetingReturned getMeetingStatus(String self) {
		HttpPost postReq = new HttpPost(STS_URL);
		postReq.setParams(createDefaultHttpParams());

		ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
		NameValuePair nvp = new BasicNameValuePair("mobile", self);
		paramList.add(nvp);
		try {
			postReq.setEntity(new UrlEncodedFormEntity(paramList, HTTP.UTF_8));
		} catch (UnsupportedEncodingException e) {
			return null;
		}

		return post(postReq);
	}
}
